package com.design.twords.fragment;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.design.twords.R;
import com.design.twords.activity.AboutActivity;
import com.design.twords.activity.HelpActivity;
import com.design.twords.activity.ListenSetActivity;
import com.design.twords.activity.RepeatSetActivity;
import com.design.twords.config.ConfigData;
import com.design.twords.database.User;
import com.design.twords.database.UserConfig;
import com.design.twords.database.UserData;
import com.design.twords.utils.MyApplication;
import com.google.android.material.snackbar.Snackbar;

import org.litepal.LitePal;

import java.io.File;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class MeFragment extends Fragment implements View.OnClickListener {
    private static final String TAG = "MeFragment";

    private TextView username, daysnumb, wordsnumb, quit;
    private RelativeLayout repeatset, listenset, help, about;
    private View view;

    private static final int LOGOUT = 106;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case LOGOUT:
                    User.logOut();
                    MyApplication.getInstance().onTerminate();
                    break;
            }
        }
    };

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.me_fragment, container, false);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        //添加到Activity 列表中
        MyApplication.getInstance().addActivity(this.getActivity());
        initView();
        initListener();
        initData();



    }

    private void initData() {
        List<UserData> userData = LitePal.where("userId = ?", ConfigData.getUserId()).find(UserData.class);
        if (userData.size() > 0){
            Log.d(TAG, userData.get(0).getNickName()+"");
            username.setText(userData.get(0).getNickName());
            daysnumb.setText(userData.get(0).getDayNumb()+"");
            wordsnumb.setText(userData.get(0).getWordNumb()+"");
        }

    }

    private void initListener() {
        quit.setOnClickListener(this);
        repeatset.setOnClickListener(this);
        listenset.setOnClickListener(this);
        help.setOnClickListener(this);
        about.setOnClickListener(this);
    }

    private void initView() {
        username = getActivity().findViewById(R.id.mefragment_name);
        daysnumb = getActivity().findViewById(R.id.mefragment_days);
        wordsnumb = getActivity().findViewById(R.id.mefragment_words);
        quit = getActivity().findViewById(R.id.mefragment_qiut);

        repeatset = getActivity().findViewById(R.id.mefragment_repeatset);
        listenset = getActivity().findViewById(R.id.mefragment_listenset);
        help = getActivity().findViewById(R.id.mefragment_help);
        about = getActivity().findViewById(R.id.mefragment_about);
    }


    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()){
            case R.id.mefragment_repeatset:
                intent.setClass(getActivity(), RepeatSetActivity.class);
                startActivity(intent);
                break;
            case R.id.mefragment_listenset:
                intent.setClass(getActivity(), ListenSetActivity.class);
                startActivity(intent);
                break;
            case R.id.mefragment_help:
                intent.setClass(getActivity(), HelpActivity.class);
                startActivity(intent);
                break;
            case R.id.mefragment_about:
                intent.setClass(getActivity(), AboutActivity.class);
                startActivity(intent);
                break;
            case R.id.mefragment_qiut:
                //删除SharedPerfernce文件
                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                builder.setTitle("提示")
                        .setMessage("即将清除您的个人数据")
                        .setNegativeButton("取消", null)
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {


                                LitePal.deleteAll(UserConfig.class,"userId = ?", ConfigData.getUserId());
                                LitePal.deleteAll(UserData.class, "userId = ?", ConfigData.getUserId());


                                File[] files = new File("/data/data/" + getActivity().getPackageName() + "/shared_prefs").listFiles();
                                deleteSharedPerference(files);
                                logout();
                                Snackbar.make(view, "登出成功", Snackbar.LENGTH_LONG).show();


                            }
                        })
                        .show();


                break;
        }
    }

    private void logout() {
        ProgressDialog progressDialog = new ProgressDialog(getActivity());
        progressDialog.setTitle("提示");
        progressDialog.setMessage("系统将在3s后退出");
        progressDialog.setCancelable(false);
        progressDialog.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                    Message message = new Message();
                    message.what = LOGOUT;
                    handler.sendMessage(message);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }

    public void deleteSharedPerference(File[] files){

        boolean flag;
        for(File itemFile : files){
            flag = itemFile.delete();
            if (flag == false) {
                deleteSharedPerference(itemFile.listFiles());
            }
        }
        Toast.makeText(getActivity(), "清除缓存成功", Toast.LENGTH_SHORT).show();
    }


    @Override
    public void onStart() {
        super.onStart();
        initData();
    }
}